package socket

var Hub *hub

func init() {
	Hub = newHub()
}

func newHub() *hub {
	return &hub{
		Broadcast:  make(chan []byte),
		Register:   make(chan *Client),
		Unregister: make(chan *Client),
		Clients:    make(map[*Client]bool),
	}
}

// Hub is a ws manager
type hub struct {
	Clients    map[*Client]bool
	Broadcast  chan []byte
	Register   chan *Client
	Unregister chan *Client
}

// Start 启动websocket服务.
func (h *hub) Start() {
	for {
		select {
		case conn := <-h.Register:
			h.Clients[conn] = true
		case conn := <-h.Unregister:
			if _, ok := h.Clients[conn]; ok {
				close(conn.Send)
				delete(h.Clients, conn)
			}
		case message := <-h.Broadcast:
			for conn := range h.Clients {
				select {
				case conn.Send <- message:
				default:
					close(conn.Send)
					delete(h.Clients, conn)
				}
			}
		}
	}
}

// Send 向连接websocket的管道chan写入数据.
func (h *hub) Send(message []byte, ignore *Client) {
	for conn := range h.Clients {
		if conn != ignore {
			conn.Send <- message
		}
	}
}
